<template>
  <div class="page-container">
    <!-- 快捷操作 -->
    <list-quick-navigation ref="listQuickNavigationRef" @change="quickNavigationChange" />
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="initData" @reset="searcherReset" />

    <table-index :table="table" @loadData="initData">
      <template #orderCode="{ record }">
        <div class="order-info-item">
          <div>{{ record.orderCode }}</div>
        </div>
        <!-- 订单标签 -->
        <a-space wrap>
          <tag type="primary" v-for="(item, index) in record.orderLabelList" :key="index">{{ item }}</tag>
        </a-space>
      </template>
      <!-- 车辆信息 -->
      <template #carInfo="{ record }">
        <div>{{ record.licenseNo }}</div>
        <div>{{ record.carModelName }}</div>
      </template>
      <!-- ETC订单状态 -->
      <template #orderStatus="{ record }">
        <span :class="['orderStatus_' + record.orderStatus]">{{ record.orderStatusName || '-' }}</span>
        <a-tooltip content="订单已到达结束时间，但存在进行中的通行记录" position="top" mini v-if="record.orderStatus == 20">
          <icon-question-circle style="color: #1890ff; margin-left: 2px" />
        </a-tooltip>
      </template>
      <!-- ETC订单周期 -->
      <template #etcDateRange="{ record }">
        <div>实际开始时间：{{ record.actualStartTime || '-' }}</div>
        <div>预计结束时间：{{ record.endTime || '-' }}</div>
        <div v-if="record.orderStatus == 30">实际结束时间：{{ record.actualEndTime || '-' }}</div>
      </template>
      <template #orderInfo="{ record }">
        <div>{{ record.refTypeName ? `自驾${record.refTypeName}` : '-' }}</div>
        <div v-if="record.refCode">
          <div>自有</div>
          <a-link class="order-info-item a-link" @click="() => toRefOrder(record)">
            {{ record.refCode }}
          </a-link>
        </div>
        <div v-if="record.channelOrderCode">
          <div>{{ record.channelTypeName }}</div>
          <a-link class="order-info-item a-link" @click="() => toRefOrder(record)">
            {{ record.channelOrderCode }}
          </a-link>
        </div>
      </template>
      <!-- ETC设备号 -->
      <template #etcCode="{ record }">
        <div>{{ record.etcCode }}</div>
        <!-- 标签 -->
        <div v-if="record.etcSourceName">
          <a-tag :color="getTagColor(record.etcSourceName)">
            {{ record.etcSourceName }}
          </a-tag>
        </div>
      </template>
    </table-index>
  </div>
  <!-- 修改ETC订单弹框 -->
  <edit-order-modal ref="editEtcModalRef" @editOk="initData" />
</template>
<!-- todoList -->
<script setup name="EtcOrderList">
  import { ref, reactive, onMounted, computed, h } from 'vue'
  import { Modal, Message } from '@arco-design/web-vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { useExport } from '@/hooks/list'
  import { usePageDict } from '@/hooks/useDict'
  import { getEtcListApi, exportExcel, closeOrderApi } from '@/api/order/etcOrder'
  import listQuickNavigation from './components/list-quick-navigation.vue'
  import editOrderModal from './components/list-modals/edit-order-modal.vue'
  import { usePermission } from '@/hooks/usePermission'

  import useNavigate from '@/hooks/useNavigate'
  const { navigateTo } = useNavigate()
  import { cloneDeep } from 'lodash-es'

  const listQuickNavigationRef = ref()
  const dict = usePageDict('getEtcOrderEnums')
  // dateTime Attrs
  const dateTimeAttrs = {
    type: 'i-range-picker',
    attrs: {
      showTime: true,
      timePickerProps: {
        defaultValue: ['00:00:00', '23:59:59'],
      },
    },
  }
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: 'ETC订单号', prop: 'orderCodeLike', placeholder: '请输入', type: 'a-input' },
      { label: '车牌号', prop: 'licenseNoLike', placeholder: '请输入', type: 'a-input' },
      { label: '关联订单号', prop: 'refCodeLike', placeholder: '请输入', type: 'a-input' },
      { label: 'ETC订单状态', prop: 'orderStatusList', type: 'a-select', options: dict.orderStatusEnums, multiple: true },
      { label: '标签', prop: 'orderLabelList', type: 'a-select', options: dict.orderLabelEnums, multiple: true },
      { label: '所属门店', prop: 'siteId', type: 'remote-select', attrs: { type: 'site_listBystaff' } },
      { label: 'ETC服务商', prop: 'etcSource', type: 'a-select', options: dict.orderSourceEnums },
      { label: '下单人手机号', prop: 'mobileLike', placeholder: '请输入', type: 'a-input', maxlength: 30 },
      { label: '车型', prop: 'carModelId', type: 'remote-select', attrs: { type: 'car_model_tenantList' } },
      {
        label: '下单时间',
        prop: 'orderCreateTimeArr',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.orderCreateTimeBegin = value[0]
          queryParam.orderCreateTimeEnd = value[1]
        },
      },
      {
        label: '实际开始时间',
        prop: 'actualStartTimeArr',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.actualStartTimeBegin = value[0]
          queryParam.actualStartTimeEnd = value[1]
        },
      },
      {
        label: '预计结束时间',
        prop: 'endTimeEndArr',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.endTimeBegin = value[0]
          queryParam.endTimeEnd = value[1]
        },
      },
      {
        label: '实际结束时间',
        prop: 'actualEndTimeArr',
        ...dateTimeAttrs,
        change: (value = []) => {
          queryParam.actualEndTimeBegin = value[0]
          queryParam.actualEndTimeEnd = value[1]
        },
      },
    ]
  })
  // 跳转长租，短租详情
  const toRefOrder = (val) => {
    if (val.refType == '1') {
      if (usePermission('svms:order:short-order.detail')) {
        navigateTo(`/short-order/detail/${val.refId}`, `${val.refCode}-短租详情`)
      }
    } else {
      if (usePermission('svms:order:long-order.detail')) {
        navigateTo(`/long-order/detail/${val.refId}`, `${val.refCode}-长租详情`)
      }
    }
  }

  // 结束订单操作
  const finishOrderFn = (record) => {
    closeOrderApi({
      id: record.id,
    }).then(() => {
      initData()
      Message.success(`已结束订单`)
    })
  }

  const defaultQueryParam = {
    // 下单时间
    orderCreateTimeArr: [],
    // 实际开始时间
    actualStartTimeArr: [],
    // 预计结束时间
    endTimeEndArr: [],
    // 实际结束时间
    actualEndTimeArr: [],
  }
  // 定义 queryParam
  const queryParam = reactive({
    ...cloneDeep(defaultQueryParam),
  })

  // 快捷导航点击事件
  const quickNavigationChange = (param) => {
    // 清空
    for (var k in queryParam) {
      queryParam[k] = undefined
    }
    // 更新数据
    let newParam = {
      ...cloneDeep(defaultQueryParam),
      ...param,
    }
    for (var k in newParam) {
      queryParam[k] = newParam[k]
    }
    loadData(1)
  }
  const editEtcModalRef = ref()
  const buttons = computed(() => {
    return [
      {
        label: '导出',
        permission: 'svms:order:etc-order.export',
        method: () => {
          useExport(exportExcel, queryParam)
        },
      },
    ]
  })

  const operates = computed(() => {
    return [
      {
        label: '详情',
        permission: 'svms:order:etc-order.detail',
        method: (record) => {
          navigateTo(`/etc-order/detail/${record.id}`, `${record.orderCode}-详情`)
        },
      },
      {
        label: '修改关联订单',
        permission: 'svms:order:etc-order.edit',
        method: (record) => {
          editEtcModalRef.value.open(record)
        },
      },
      {
        label: '结束订单',
        show: (record) => record.orderStatus == 10,
        permission: 'svms:order:etc-order.finish',
        method: (record) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认结束',
            width: '480px',
            content: h('div', null, [
              h('p', null, `请确认是否结束${record.licenseNo}的ETC租赁订单？`),
              h('p', { style: { color: 'red', marginTop: '20px' } }, `ETC租赁订单结束后，用车人将无法继续使用，可能造成经济损失。`),
            ]),
            onOk: () => {
              finishOrderFn(record)
            },
          })
        },
      },
    ]
  })
  // table 配置
  const table = useTable({
    columns: [
      { title: 'ETC订单号', slotName: 'orderCode', width: 240, fixed: 'left' },
      { title: 'ETC设备号', dataIndex: 'etcCode', width: 180, slotName: 'etcCode' },
      { title: '车辆信息', slotName: 'carInfo', width: 180 },
      { title: '所属门店', dataIndex: 'siteName', width: 180 },
      { title: 'ETC订单状态', slotName: 'orderStatus', width: 120 },
      { title: '下单人手机号', dataIndex: 'mobile', width: 140 },
      { title: 'ETC订单周期', slotName: 'etcDateRange', width: 270 },
      { title: 'ETC租期', dataIndex: 'rentDays', width: 100 },
      { title: 'ETC租赁费用', dataIndex: 'amt', unit: '元', width: 140 },
      { title: '关联订单', slotName: 'orderInfo', width: 220 },
      { title: '下单时间', dataIndex: 'orderCreateTime', width: 180 },
    ],
    bordered: {
      wrapper: true,
      cell: true,
    },
    tableLoading: false,
    operates: operates.value,
    buttons: buttons.value,
  })
  // 列表接口调用
  const loadData = useFetchTableDataApi(table, queryParam, getEtcListApi)
  // 重置
  const searcherReset = () => {
    listQuickNavigationRef.value.reset()
    listQuickNavigationRef.value.getStNum()
  }

  // 操作后的初始化
  const initData = () => {
    // 列表初始化
    loadData()
    // 列表快捷导航初始化
    listQuickNavigationRef.value.getStNum()
  }

  // 根据标签内容返回不同的颜色值
  const getTagColor = (label) => {
    const tagColors = {
      好人好车: 'orange',
      量子: 'arcoblue',
    }
    return tagColors[label] || 'blue'
  }

  onMounted(() => {
    loadData()
  })
</script>

<style lang="less" scoped>
  .orderStatus {
    &_10 {
      color: #00b42a;
    }
    &_20 {
      color: #ff7d00;
    }
  }
  .warn-text {
    color: red;
  }
  .a-link {
    color: rgba(24, 144, 255, 1);
  }
  .order-info-item + .order-info-item {
    margin-top: 4px;
  }
  .staffText {
    max-width: 86px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
